package cc.idoone.spring_boot_hello.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理(不能处理404页面找不到, 参考 ErrorController)
 *
 * @author hemj
 * @version 2017/9/22
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	public static final String DEFAULT_ERROR_VIEW = "error/50x";

	/**
	 * 统一异常处理：所有异常
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", e);
		mav.addObject("url", req.getRequestURL());
		mav.setViewName(DEFAULT_ERROR_VIEW);
		e.printStackTrace();
		return mav;
	}

	/**
	 * 统一异常处理：运行时异常
	 */
	@ExceptionHandler({RuntimeException.class})
	@ResponseStatus(HttpStatus.OK)
	public ModelAndView runtimeExceptionHandler(HttpServletRequest req, RuntimeException e) throws Exception {
		return defaultErrorHandler(req, e);
	}

	/**
	 * 统一异常处理：具体异常
	 */
	@ExceptionHandler(value = IllegalArgumentException.class)
	public ModelAndView illegalArgumentExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
		return defaultErrorHandler(req, e);
	}

	/**
	 * 统一异常处理：文件上传异常
	 */
	@ExceptionHandler(value = {MissingServletRequestPartException.class, MultipartException.class})
	public ModelAndView fileUploadExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
		return defaultErrorHandler(req, e);
	}

	/**
	 * 统一异常处理：返回数据
	 */
	@ExceptionHandler(value = WebappException.class)
	@ResponseBody
	public ErrorInfo<String> dataErrorHandler(HttpServletRequest req, WebappException e) throws Exception {
		ErrorInfo<String> r = new ErrorInfo<>();
		r.setMessage(e.getMessage());
		r.setCode(ErrorInfo.ERROR);
		r.setData("Some Data");
		r.setUrl(req.getRequestURL().toString());
		return r;
	}

}
